const { createOrderUrl, skuUrl, wxPayUrl, payResultUrl, orderSuccessUrl } = require("../../config");
const { http } = require("../../util/http");
// const QRCode = require('qrcode/lib/browser')
let flag;
let ti;
Page({
  data: {
    products: [],
    carts: [],
    total: 0,
    no: 0,
    status: 1,
    spus: [],
    tmp: [],
    isPay: false,
    payUrl: null,
    selectedName: null,
    selectedPrice: null,
    mNo:'Bar'
  },
  onLoad() {
    const data = [];
    http(skuUrl, 'get').then(res => {
      res.forEach(spu => {
        const img = JSON.parse(spu.imgs || '[]')[0]?.url
        spu.skus.forEach(sku => {
          data.push({
            ...sku,
            name: JSON.parse(sku.combination || '[]').reduce((name, combination) => {
              name += combination.value
              return name
            }, sku.name + '_'),
            img
          })
        })
      })
      this.setData({
        spus: res,
        products:data,
        tmp: data
      })
    })
  },
  addProduct: function(e, type) {
    const id = e.currentTarget.dataset.productId
    const product = this.data.products.find(product => product.id === id);
    const cartProductIndex = this.data.carts.findIndex(product =>product.id === id);
    if (cartProductIndex > -1) {
      const cartProduct = this.data.carts[cartProductIndex];
      if (type === 'minus') {
        if (cartProduct.no !== 1) {
          cartProduct.no -= 1;
          this.data.carts.splice(cartProductIndex, 1, cartProduct);
        } else {
          this.data.carts.splice(cartProductIndex, 1);
        }
      } else {
        cartProduct.no += 1;
        this.data.carts.splice(cartProductIndex, 1, cartProduct);
      }
    } else {
      product.no = 1;
      this.data.carts.push(product);
    }
    this.setData({
      carts: this.data.carts,
      total: this.data.carts.reduce((total, product) => {
        total += Number(product.price) * Number(product.no);
        return total;
      }, 0),
      no: this.data.carts.reduce((no, product) => {
        no += Number(product.no);
        return no;
      }, 0)
    })
  },
  minusItemProduct(e) {
    this.addProduct(e, 'minus')
    
  },
  plusItemProduct(e) {
    this.addProduct(e)
  },
  clearCart() {
    this.setData({
      total: 0,
      no: 0,
      carts: [],
      mNo:'Bar'
    })
  },
  displayProductDetail() {
    this.setData({
      status:2
    })
  },
  bindKeyInput(e) {
    const value = e.detail.value;
    const timer = setTimeout(() => {
      if (flag) {
        clearTimeout(timer);
        return
      }
      flag = true;
      const data = this.data.tmp;
      this.setData({
        products: data.filter(d => {
          return d.name.includes(value)
        })
      })
      clearTimeout(timer)
      flag=  false
    }, 500);
  },
  closeMask() {
    this.setData({
      status: 1
    })
  },
  back() {
    clearInterval(ti);
    ti = null;
    this.setData({
      isPay:false,
      dataURL: null,
      selectedName: null,
      selectedPrice: null
    })
  },
  repeatPayResult(orders) {
    ti = setInterval(() => {
      http(payResultUrl, 'get', { order:  orders[0]?.muster_order_id}, {}, 'json', true).then(res => {
        if (!res) {
          // @tod
        } else {
          clearInterval(ti)
          ti = null;
          tt.showToast({
            title: '支付成功'
          })
          http(orderSuccessUrl, 'post', { musterOrderId: orders[0]?.muster_order_id }).then(res => {
            console.log('res', res);
            if (!res) {
              // @todo
            } else {
              this.back()
              // 清空购物车
              this.clearCart()
            }
          })
        }
      })
    }, 1000)
  },
  gopay() {
    tt.showPrompt({
      "title": "这是个输入机器号",
      "maxLength": 50,
      "confirmText": "确定",
      "cancelText": "取消",
      success: res => {
        const no = res.inputValue;
        if (res.confirm) {
          this.setData({
            mNo: no
          })
          http(createOrderUrl, 'post', {skus: this.data.carts, no}).then(res =>{
            const orders = res;
            const selectedName = orders.reduce((name, order) => {
              name += `${order.name.split('_')?.[0]},`
              return name
            }, '');
            const selectedPrice = orders.reduce((money, order) => {
              money += Number(order.total) * Number(order.price);
              return money;
            }, 0);
            http(wxPayUrl, 'post', {
              orderNo: orders[0]?.muster_order_id,
              amount: selectedPrice,
              name: selectedName,
              requireImg: true
            }).then(res => {
              this.setData({
                payUrl: res.dataURL,
                isPay:true,
                selectedName,
                selectedPrice
              })
              this.repeatPayResult(orders)
            })
          })
        }
      },
      fail(res) {
        console.log(`showPrompt fail: ${JSON.stringify(res)}`);
      }
    });
  }
})